<template>
  <div class="system-container">
    <div class="header">
      <h2>系统设置</h2>
    </div>

    <el-tabs v-model="activeTab" class="system-tabs">
      <el-tab-pane label="基本设置" name="basic">
        <div v-loading="loading.basic" class="setting-form">
          <el-form
            ref="basicFormRef"
            :model="basicForm"
            :rules="basicRules"
            label-width="120px"
          >
            <el-form-item label="博物馆名称" prop="museum_name">
              <el-input v-model="basicForm.museum_name" placeholder="请输入博物馆名称" />
            </el-form-item>
            <el-form-item label="开放时间" prop="open_time">
              <el-input v-model="basicForm.open_time" placeholder="如：周二至周日 9:00-17:00" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contact_phone">
              <el-input v-model="basicForm.contact_phone" placeholder="请输入联系电话" />
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="basicForm.address" placeholder="请输入博物馆地址" />
            </el-form-item>
            <el-form-item label="每日最大预约数" prop="max_reservation">
              <el-input-number v-model="basicForm.max_reservation" :min="1" :max="1000" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="saveBasicSettings(basicFormRef)">保存</el-button>
              <el-button @click="resetBasicForm(basicFormRef)">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>

      <el-tab-pane label="管理员设置" name="admin">
        <div v-loading="loading.admin" class="admin-list">
          <div class="admin-header">
            <h3>管理员列表</h3>
            <el-button type="primary" @click="dialogVisible = true">添加管理员</el-button>
          </div>
          
          <el-table :data="adminList" border style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="role" label="角色">
              <template #default="scope">
                <el-tag :type="scope.row.role === '2' ? 'danger' : 'primary'">
                  {{ scope.row.role === '2' ? '超级管理员' : '普通管理员' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" />
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button
                  v-if="scope.row.username !== 'admin'"
                  size="small"
                  type="danger"
                  @click="deleteAdmin(scope.row.id)"
                >
                  删除
                </el-button>
                <el-button
                  size="small"
                  @click="resetPassword(scope.row.id)"
                >
                  重置密码
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加管理员对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="添加管理员"
      width="500px"
    >
      <el-form
        ref="adminFormRef"
        :model="adminForm"
        :rules="adminRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="adminForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="adminForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="adminForm.confirmPassword" type="password" placeholder="请再次输入密码" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="adminForm.role" placeholder="请选择角色">
            <el-option label="超级管理员" value="2" />
            <el-option label="普通管理员" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAdmin(adminFormRef)">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getSystemSettings, 
  updateSystemSettings, 
  getAdminList,
  addAdmin,
  deleteAdmin as deleteAdminApi,
  resetAdminPassword
} from '@/api/admin'

const activeTab = ref('basic')
const loading = reactive({
  basic: false,
  admin: false
})
const dialogVisible = ref(false)

// 基本设置表单
const basicFormRef = ref(null)
const basicForm = reactive({
  museum_name: '',
  open_time: '',
  contact_phone: '',
  address: '',
  max_reservation: 200
})

// 基本设置表单验证规则
const basicRules = reactive({
  museum_name: [
    { required: true, message: '请输入博物馆名称', trigger: 'blur' }
  ],
  open_time: [
    { required: true, message: '请输入开放时间', trigger: 'blur' }
  ],
  contact_phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入博物馆地址', trigger: 'blur' }
  ]
})

// 管理员列表
const adminList = ref([])

// 管理员表单
const adminFormRef = ref(null)
const adminForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  role: '1'
})

// 管理员表单验证规则
const adminRules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== adminForm.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
})

// 获取基本设置
const fetchSystemSettings = async () => {
  loading.basic = true
  try {
    const res = await getSystemSettings()
    const data = res.data
    basicForm.museum_name = data.museum_name
    basicForm.open_time = data.open_time
    basicForm.contact_phone = data.contact_phone
    basicForm.address = data.address
    basicForm.max_reservation = data.max_reservation
  } catch (error) {
    console.error('获取系统设置失败', error)
    ElMessage.error('获取系统设置失败')
  } finally {
    loading.basic = false
  }
}

// 获取管理员列表
const fetchAdminList = async () => {
  loading.admin = true
  try {
    const res = await getAdminList()
    adminList.value = res.data
  } catch (error) {
    console.error('获取管理员列表失败', error)
    ElMessage.error('获取管理员列表失败')
  } finally {
    loading.admin = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchSystemSettings()
  fetchAdminList()
})

// 保存基本设置
const saveBasicSettings = async (formEl) => {
  if (!formEl) return
  
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        await updateSystemSettings(basicForm)
        ElMessage.success('保存成功')
      } catch (error) {
        console.error('保存系统设置失败', error)
        ElMessage.error('保存系统设置失败')
      }
    } else {
      return false
    }
  })
}

// 重置基本设置表单
const resetBasicForm = (formEl) => {
  if (!formEl) return
  fetchSystemSettings()
}

// 保存管理员
const saveAdmin = async (formEl) => {
  if (!formEl) return
  
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        await addAdmin({
          username: adminForm.username,
          password: adminForm.password,
          role: adminForm.role
        })
        ElMessage.success('添加成功')
        dialogVisible.value = false
        adminForm.username = ''
        adminForm.password = ''
        adminForm.confirmPassword = ''
        adminForm.role = '2'
        fetchAdminList()
      } catch (error) {
        console.error('添加管理员失败', error)
        ElMessage.error('添加管理员失败')
      }
    } else {
      return false
    }
  })
}

// 删除管理员
const deleteAdmin = (id) => {
  ElMessageBox.confirm('确定要删除该管理员吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteAdminApi(id)
      ElMessage.success('删除成功')
      fetchAdminList()
    } catch (error) {
      console.error('删除管理员失败', error)
      ElMessage.error('删除管理员失败')
    }
  }).catch(() => {})
}

// 重置密码
const resetPassword = (id) => {
  ElMessageBox.confirm('确定要重置该管理员的密码吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await resetAdminPassword(id)
      ElMessage.success(`密码重置成功，新密码: ${res.data.password}`)
    } catch (error) {
      console.error('重置密码失败', error)
      ElMessage.error('重置密码失败')
    }
  }).catch(() => {})
}
</script>

<style scoped>
.system-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.system-tabs {
  max-width: 1000px;
}

.setting-form {
  max-width: 600px;
  margin-top: 20px;
}

.admin-list {
  margin-top: 20px;
}

.admin-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style> 